package main

//https://www.cnblogs.com/cheyunhua/p/17514375.html 疑问：没测试完成
import (
	"encoding/json"
	"fmt"
	"net/http"
)

type User struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
	Age  int    `json:"age"`
}

var users []User

func main() {
	http.HandleFunc("/users", getUsersHandler)
	http.HandleFunc("/users/create", createUserHandler)

	fmt.Println("Server is listening on port 8080...")
	fmt.Println("ListenAndServe:", http.ListenAndServe(":8080", nil))
	//log.Fatal(http.ListenAndServe(":8080", nil))
	//疑问： log.Fatal与log.Println的区别；
}

func getUsersHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	// 返回所有用户数据
	json.NewEncoder(w).Encode(users)
}

func createUserHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	// 解析请求体中的JSON数据
	var newUser User
	err := json.NewDecoder(r.Body).Decode(&newUser)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// 生成新用户ID
	newUser.ID = len(users) + 1

	// 添加新用户到列表中
	users = append(users, newUser)

	// 返回新创建的用户信息
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(newUser)
}
